/**
 * 文本对比组件
 * 提供文本差异对比和替换功能
 */

import React, { useState, useCallback, useMemo } from 'react'
import { useAIWriter } from '../../hooks/ai'
import { Button } from '../ui/Button'
import {
  GitCompare,
  ArrowLeft,
  ArrowRight,
  Check,
  X,
  Loader2,
  Eye,
  EyeOff
} from 'lucide-react'

interface TextComparisonProps {
  originalText: string
  modifiedText: string
  onAcceptChanges?: (newText: string) => void
  onRejectChanges?: () => void
  className?: string
}

interface DiffSegment {
  type: 'equal' | 'insert' | 'delete' | 'replace'
  original: string
  modified: string
  lineNumber: number
}

export const TextComparison: React.FC<TextComparisonProps> = ({
  originalText,
  modifiedText,
  onAcceptChanges,
  onRejectChanges,
  className = '',
}) => {
  const [currentChangeIndex, setCurrentChangeIndex] = useState(0)
  const [showAccepted, setShowAccepted] = useState(true)
  const [isImproving, setIsImproving] = useState(false)
  const [improvedText, setImprovedText] = useState('')
  const { polish } = useAIWriter()

  // 计算文本差异
  const diffSegments = useMemo(() => {
    return calculateDiff(originalText, modifiedText)
  }, [originalText, modifiedText])

  // 获取变更列表
  const changes = useMemo(() => {
    return diffSegments.filter(segment => segment.type !== 'equal')
  }, [diffSegments])

  // 当前变更
  const currentChange = changes[currentChangeIndex]

  // 接受当前变更
  const acceptChange = useCallback(() => {
    if (currentChange) {
      setShowAccepted(true)
      if (currentChangeIndex === changes.length - 1) {
        // 所有变更都已接受
        onAcceptChanges?.(modifiedText)
      }
    }
  }, [currentChange, currentChangeIndex, changes.length, onAcceptChanges, modifiedText])

  // 拒绝当前变更
  const rejectChange = useCallback(() => {
    if (currentChange) {
      // 这里可以实现拒绝变更的逻辑
      // 例如恢复原始文本的部分内容
      if (currentChangeIndex === changes.length - 1) {
        onRejectChanges?.()
      }
    }
  }, [currentChange, currentChangeIndex, changes.length, onRejectChanges])

  // 导航到下一个变更
  const nextChange = useCallback(() => {
    if (currentChangeIndex < changes.length - 1) {
      setCurrentChangeIndex(prev => prev + 1)
    }
  }, [currentChangeIndex, changes.length])

  // 导航到上一个变更
  const previousChange = useCallback(() => {
    if (currentChangeIndex > 0) {
      setCurrentChangeIndex(prev => prev - 1)
    }
  }, [currentChangeIndex])

  // AI改进当前变更
  const improveChange = useCallback(async () => {
    if (!currentChange) return

    setIsImproving(true)
    try {
      let improved = ''

      switch (currentChange.type) {
        case 'insert':
          improved = await polish(currentChange.modified, { style: 'formal' })
          break
        case 'replace':
          improved = await polish(currentChange.modified, { style: 'clear' })
          break
        case 'delete':
          // 对于删除操作，可以提供替代建议
          improved = await polish(
            `请为以下内容提供一个更好的替代方案，而不是删除：${currentChange.original}`,
            { style: 'constructive' }
          )
          break
        default:
          improved = currentChange.modified
      }

      setImprovedText(improved)
    } catch (error) {
      console.error('AI improvement failed:', error)
    } finally {
      setIsImproving(false)
    }
  }, [currentChange, polish])

  // 应用AI改进
  const applyImprovement = useCallback(() => {
    if (improvedText && currentChange) {
      // 这里需要更新modifiedText
      // 简化实现：在实际应用中需要更复杂的文本替换逻辑
      const newModifiedText = modifiedText.replace(currentChange.modified, improvedText)
      onAcceptChanges?.(newModifiedText)
      setImprovedText('')
    }
  }, [improvedText, currentChange, modifiedText, onAcceptChanges])

  // 渲染差异段落
  const renderDiffSegment = (segment: DiffSegment, index: number) => {
    const isCurrentChange = currentChange && changes[currentChangeIndex] === segment
    const isChange = segment.type !== 'equal'
    const isAccepted = showAccepted && isChange

    let className = 'py-1 px-2 rounded '
    let bgColor = ''

    switch (segment.type) {
      case 'equal':
        bgColor = 'bg-transparent'
        break
      case 'insert':
        bgColor = 'bg-green-100 border-l-4 border-green-500'
        break
      case 'delete':
        bgColor = 'bg-red-100 border-l-4 border-red-500'
        break
      case 'replace':
        bgColor = 'bg-yellow-100 border-l-4 border-yellow-500'
        break
    }

    className += bgColor

    if (isCurrentChange) {
      className += ' ring-2 ring-blue-500'
    }

    if (isChange && !isAccepted) {
      className += ' opacity-75'
    }

    return (
      <div key={index} className={className}>
        {segment.type === 'equal' && (
          <div className="text-gray-700">
            <span className="text-xs text-gray-400 mr-2">第{segment.lineNumber}行</span>
            {segment.original}
          </div>
        )}

        {segment.type === 'insert' && (
          <div>
            <div className="flex items-center space-x-2 mb-1">
              <span className="text-xs text-green-600 font-medium">插入</span>
              <span className="text-xs text-gray-400">第{segment.lineNumber}行</span>
            </div>
            <div className="text-green-800">
              <span className="text-green-600">+</span> {segment.modified}
            </div>
          </div>
        )}

        {segment.type === 'delete' && (
          <div>
            <div className="flex items-center space-x-2 mb-1">
              <span className="text-xs text-red-600 font-medium">删除</span>
              <span className="text-xs text-gray-400">第{segment.lineNumber}行</span>
            </div>
            <div className="text-red-800 line-through">
              <span className="text-red-600">-</span> {segment.original}
            </div>
          </div>
        )}

        {segment.type === 'replace' && (
          <div>
            <div className="flex items-center space-x-2 mb-1">
              <span className="text-xs text-yellow-600 font-medium">替换</span>
              <span className="text-xs text-gray-400">第{segment.lineNumber}行</span>
            </div>
            <div className="text-red-800 line-through mb-1">
              <span className="text-red-600">-</span> {segment.original}
            </div>
            <div className="text-green-800">
              <span className="text-green-600">+</span> {segment.modified}
            </div>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className={`text-comparison bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      {/* 头部统计 */}
      <div className="border-b border-gray-200 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <GitCompare className="h-5 w-5 text-blue-500" />
            <h3 className="font-medium">文本对比</h3>
          </div>

          <div className="flex items-center space-x-4 text-sm text-gray-600">
            <span>总变更: {changes.length}</span>
            <span className="text-green-600">
              +{changes.filter(c => c.type === 'insert').length} 插入
            </span>
            <span className="text-red-600">
              -{changes.filter(c => c.type === 'delete').length} 删除
            </span>
            <span className="text-yellow-600">
              ~{changes.filter(c => c.type === 'replace').length} 替换
            </span>
          </div>
        </div>
      </div>

      {/* 变更导航 */}
      {changes.length > 0 && (
        <div className="border-b border-gray-200 p-4 bg-gray-50">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="outline"
                size="sm"
                onClick={previousChange}
                disabled={currentChangeIndex === 0}
              >
                <ArrowLeft className="h-4 w-4" />
              </Button>

              <span className="text-sm">
                变更 {currentChangeIndex + 1} / {changes.length}
              </span>

              <Button
                variant="outline"
                size="sm"
                onClick={nextChange}
                disabled={currentChangeIndex === changes.length - 1}
              >
                <ArrowRight className="h-4 w-4" />
              </Button>
            </div>

            <div className="flex items-center space-x-2">
              <label className="flex items-center space-x-1 text-sm">
                <input
                  type="checkbox"
                  checked={showAccepted}
                  onChange={(e) => setShowAccepted(e.target.checked)}
                  className="rounded"
                />
                <span>显示已接受</span>
              </label>
            </div>
          </div>

          {/* 当前变更操作 */}
          {currentChange && (
            <div className="mt-3 p-3 bg-white border border-gray-200 rounded">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <span className="text-sm font-medium">
                    {currentChange.type === 'insert' && '插入内容'}
                    {currentChange.type === 'delete' && '删除内容'}
                    {currentChange.type === 'replace' && '替换内容'}
                  </span>
                </div>

                <div className="flex items-center space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={improveChange}
                    disabled={isImproving}
                  >
                    {isImproving ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin mr-1" />
                        AI改进中...
                      </>
                    ) : (
                      'AI改进'
                    )}
                  </Button>

                  {improvedText && (
                    <div className="flex items-center space-x-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={applyImprovement}
                      >
                        应用改进
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setImprovedText('')}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  )}

                  <Button
                    variant="outline"
                    size="sm"
                    onClick={rejectChange}
                  >
                    <X className="h-4 w-4 mr-1" />
                    拒绝
                  </Button>

                  <Button
                    variant="default"
                    size="sm"
                    onClick={acceptChange}
                  >
                    <Check className="h-4 w-4 mr-1" />
                    接受
                  </Button>
                </div>
              </div>

              {/* AI改进建议 */}
              {improvedText && (
                <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded">
                  <div className="flex items-center space-x-2 mb-2">
                    <Eye className="h-4 w-4 text-blue-600" />
                    <span className="text-sm font-medium text-blue-800">AI改进建议</span>
                  </div>
                  <p className="text-sm text-blue-700">{improvedText}</p>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* 文本对比内容 */}
      <div className="p-4 max-h-96 overflow-y-auto">
        {changes.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <GitCompare className="h-12 w-12 mx-auto mb-3 text-gray-300" />
            <p>没有检测到文本差异</p>
          </div>
        ) : (
          <div className="font-mono text-sm">
            {diffSegments.map((segment, index) => renderDiffSegment(segment, index))}
          </div>
        )}
      </div>

      {/* 底部操作 */}
      <div className="border-t border-gray-200 p-4 bg-gray-50">
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-600">
            {changes.length > 0 && (
              <span>正在查看第 {currentChangeIndex + 1} 个变更，共 {changes.length} 个</span>
            )}
          </div>

          <div className="flex items-center space-x-2">
            {changes.length > 0 && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  onAcceptChanges?.(modifiedText)
                }}
              >
                接受所有变更
              </Button>
            )}

            <Button
              variant="ghost"
              size="sm"
              onClick={onRejectChanges}
            >
              拒绝所有变更
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}

// 简化的文本差异计算算法
function calculateDiff(original: string, modified: string): DiffSegment[] {
  const originalLines = original.split('\n')
  const modifiedLines = modified.split('\n')
  const segments: DiffSegment[] = []

  let originalIndex = 0
  let modifiedIndex = 0

  while (originalIndex < originalLines.length || modifiedIndex < modifiedLines.length) {
    const originalLine = originalLines[originalIndex]
    const modifiedLine = modifiedLines[modifiedIndex]

    if (originalIndex >= originalLines.length) {
      // 只有新增行
      segments.push({
        type: 'insert',
        original: '',
        modified: modifiedLine || '',
        lineNumber: modifiedIndex + 1,
      })
      modifiedIndex++
    } else if (modifiedIndex >= modifiedLines.length) {
      // 只有删除行
      segments.push({
        type: 'delete',
        original: originalLine || '',
        modified: '',
        lineNumber: originalIndex + 1,
      })
      originalIndex++
    } else if (originalLine === modifiedLine) {
      // 相同行
      segments.push({
        type: 'equal',
        original: originalLine,
        modified: modifiedLine,
        lineNumber: originalIndex + 1,
      })
      originalIndex++
      modifiedIndex++
    } else {
      // 不同行 - 简化为替换
      segments.push({
        type: 'replace',
        original: originalLine,
        modified: modifiedLine,
        lineNumber: originalIndex + 1,
      })
      originalIndex++
      modifiedIndex++
    }
  }

  return segments
}